import axios from 'axios';
import { validatenull } from './validate'
import { Toast } from 'antd-mobile'
import {store} from '@/Store/index';

// 配置API接口地址
let baseUrl = "";
// let baseUrl = 'https://mobile-elmcq-prod.adient.com.cn:6379' // 'https://mobile-elmcq-prod.adient.com.cn:6379' //'http://124.70.213.53'

// 自定义判断元素类型
function toType(obj) {
    return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// 参数过滤函数
function filterNull(o) {
    for (let key in o) {
        if (o[key] === null) {
            delete o[key]
        }
    }
    return o
}

// 工具方法
function toParams(obj) {
    let param = ''
    for (const name in obj) {
        if (typeof obj[name] !== 'function') {
            param += '&' + name + '=' + encodeURI(obj[name])
        }
    }
    return param.substring(1)
}
function apiStream({ method, url, params, headers }) {
    if (params) {
        params = filterNull(params)
    }

    let whiteListUrl = [
        // '/auth-v3/oauth/token',
        '/adient-pms/pc/app/getByType',
        '/adient-pms/pc/base/workShop',
        '/adient-pms/api/checkTicket',
        '/admin-v3/user/'
    ]

    return new Promise(async (resolve, reject) => {
        let otherUrl = "",body = '';
        if (method.toLowerCase() === 'get') {
            if (!validatenull(params)) {
                otherUrl = '?' + toParams(params)
            }
        } else {
            body = JSON.stringify(params);
        }
        let host = baseUrl;
        let headersObj = {
            'Authorization': 'Bearer ' + store.getState().token,
            'site': store.getState().site || "",
            'client-id': 'mes-hofo',
            'cataType': 'mes-hofo',
            'corp-code': 'MES-HOFO',
            'Content-Type': 'application/json; text/plain',
            ...headers,
        }

        for (const u of whiteListUrl) {
            if (url.indexOf(u) > -1) {
                delete headersObj.Authorization
            }
        }

        axios(host + url + otherUrl, {
            method: method,
            type: 'json',
            headers: headersObj,
            data: body,
            timeout: 30000
        }).then((res) => {
            if (res.status === 401) {
                Toast.show({
                    content: '用户未登录',
                })
            } else {
                if (res.status == -1) {
                    Toast.show({
                        content: '网络异常，请检查!',
                    })
                }
            }
            resolve(res);
        })
            .catch((error) => {
                console.log(error, 'error');
                if (error == 401) {
                    Toast.show({
                        content: ' 您没有任何权限，无法登录系统！请联系管理员添加！',
                    })
                }
                reject(error);
            });
    });
}

function get(option) {
    return apiStream({
        ...option,
        method: 'GET'
    });
}
function post(option) {
    return apiStream({
        ...option,
        method: 'POST'
    });
}
function put(option) {
    return apiStream({
        ...option,
        method: 'PUT'
    });
}
function del(option) {
    return apiStream({
        ...option,
        method: 'DELETE'
    });
}
function request(option) {
    return apiStream(option);
}

export { baseUrl, get, post, put, del, request };
